<template>
  <el-dialog
    :title="$t('给我们留言')"
    custom-class="contactUs"
    :visible.sync="visible"
    width="330px"
    :append-to-body="true"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :lock-scroll="false"
    :modal="false"
  >
    <div class="content">
      <el-form ref="form" v-loading="messageLoading" :label-position="labelPosition" :rules="rules" :model="form">
        <el-form-item :label="$t('您所在机构')" prop="code">
          <el-input v-model="form.code" size="mini" show-word-limit maxlength="100" clearable />
        </el-form-item>
        <el-form-item :label="$t('您的电话')" prop="phone">
          <el-input v-model="form.phone" size="mini" clearable />
        </el-form-item>
        <el-form-item :label="$t('留言内容')" prop="remark">
          <el-input v-model="form.remark" type="textarea" show-word-limit maxlength="2000" :rows="2" clearable />
        </el-form-item>
        <div>
          <el-button type="primary" size="small" @click="onSubmit">{{ $t('提交') }}</el-button>
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>
<script>
import { recordMessage } from '@/api/login.js'
export default {
  name: 'ContactUs',
  data() {
    var checkPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请输入联系方式')))
      } else {
        let regPone = null
        // 最新16手机正则
        var mobile = /^1(3|4|5|6|7|8|9)\d{9}$/
        // 座机
        var tel = /^\d{3,4}-?\d{7,9}$/
        // charAt查找第一个字符方法，用来判断输入的是座机还是手机号
        if (value.charAt(0) === 0 || value.charAt(0) === '0') {
          regPone = tel
          console.log('固话')
        } else {
          regPone = mobile
          console.log('手机')
        }
        if (!regPone.test(value)) {
          return callback(
            new Error(this.$t('请填写联系人电话(座机: \'区号-座机号码\')'))
          )
        }
        callback()
      }
    }
    return {
      labelPosition: 'top',
      form: {
        code: '',
        phone: '',
        remark: ''
      },
      rules: {
        code: [{ required: true, trigger: 'blur', message: this.$t('必填信息') }],
        phone: [{ required: true, trigger: 'blur', validator: checkPhone }],
        remark: [{ required: true, trigger: 'blur', message: this.$t('必填信息') }]
      },
      visible: false,
      messageLoading: false
    }
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.messageLoading = true
          recordMessage(this.form).then(response => {
            if (response.data.code === 0) {
              this.msgSuccess(this.$t('发送成功!'))
              this.visible = false
            }
            this.messageLoading = false
          })
        }
      })
    }

  }
}
</script>
